#include <unistd.h>
#include <wiringPi.h>
#include "tn901.h"
#include <stdio.h>

//TN901 is master.
#define SPI_SCLK_Pin 20
#define SPI_MOSI_Pin 21
#define TN901_ACTION_Pin 16

#define SPI_SCLK_RD() digitalRead(SPI_SCLK_Pin)
#define SPI_MOSI_RD() digitalRead(SPI_MOSI_Pin)
#define TN901_ACT_SET() digitalWrite(TN901_ACTION_Pin, HIGH)
#define TN901_ACT_CLR() digitalWrite(TN901_ACTION_Pin, LOW)


static TN901_Structure htn901;

void SPI_init(void) {
    wiringPiSetupGpio();
    pinMode(SPI_SCLK_Pin, INPUT);
    pinMode(SPI_MOSI_Pin, INPUT);
	pinMode(TN901_ACTION_Pin, OUTPUT);
    //pullUpDnControl(SPI_SCLK_Pin, PUD_UP);
    //pullUpDnControl(SPI_MOSI_Pin, PUD_UP);
	
	TN901_ACT_CLR();
    sleep(1);
}

uint8_t SPI_Read_Byte(void) {
    uint8_t ret;
    for (int i = 0; i < 8; ++i) {
        while (HIGH == SPI_SCLK_RD());
        ret = (ret << 1) | SPI_MOSI_RD();
		while (LOW == SPI_SCLK_RD());
	}
	return ret;
}

void tn901_init(void) {
    SPI_init();
}

bool tn901_receive_message(void) {
	uint8_t item, dath, datl, sum, cr;
    item = SPI_Read_Byte();
    dath = SPI_Read_Byte();
    datl = SPI_Read_Byte();
    sum = SPI_Read_Byte();
    cr = SPI_Read_Byte();

//    if (0x0d == cr) {
//		printf("item = %x, dath = %x, datl = %x, sum = %x, r = %x\n", item, dath, datl, sum, cr);
//		return false;
//    }
    if (item + dath + datl != sum) {
        return false;
    }
    if (0x4c == item) {
        htn901.obj_temp = ((dath << 8) + datl)/16.0 - 273.15;
    }
   	else if (0x66 == item)
	{
        htn901.amb_temp = ((dath << 8) + datl)/16.0 - 273.15;
    }
    return true;
}

bool tn901_readTemp(void) {
	TN901_ACT_SET();
	usleep(10000);
	tn901_receive_message();
	TN901_ACT_CLR();
	usleep(10000);
	tn901_receive_message();

//	TN901_ACT_CLR();
//	usleep(10000);
//	tn901_receive_message();
//	TN901_ACT_SET();
//	usleep(10000);
//	tn901_receive_message();

	return true;
}

float get_objTemp(void) {
    return htn901.obj_temp;
}

float get_ambTemp(void) {
    return htn901.amb_temp;
}

